package com.filetransfer.app.ui.upload;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.filetransfer.api.ShareCollection;
import com.filetransfer.api.upload.ProgressInfo;
import com.filetransfer.app.R;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FileAdapter extends RecyclerView.Adapter<FileAdapter.FileViewHolder> {
    public FileAdapter(OnFileRemoveListener onFileRemoveListener) {
        this.onFileRemoveListener = onFileRemoveListener;
    }
    //        (position, progress) -> {
//            // 在此更新特定位置的文件的进度
//            View view = recyclerView.getLayoutManager().findViewByPosition(position);
//            if (view != null) {
//                ProgressBar progressBar = view.findViewById(R.id.uploadProgressBar);
//                if (progressBar != null) {
//                    progressBar.setProgress(progress);
//                }
//            }
//        }
    private final List<FileInfo> fileList = new ArrayList<>();
    private final OnFileRemoveListener onFileRemoveListener;
    @Getter
    private ShareCollection apiClient = new ShareCollection(
            // chunkSize: 分片大小
            // 10MB
            10 * 1024 * 1024);
    public void clear() {
        fileList.clear();
        notifyDataSetChanged();
    }
    public interface makeShareResult {
        void makeShare(ShareCollection.ShareResultToken result);
    }
    public void makeShare(makeShareResult callback, Consumer<Exception> onError) {
        new Thread(() -> {
            try {
                // 创建分享
                var shareResult = apiClient.makeShare();
                callback.makeShare(shareResult);
            } catch (Exception e) {
                log.error("上传分享失败", e);
                onError.accept(e);
            }
        }).start();
    }
    public interface OnFileRemoveListener {
        void onFileRemove(FileInfo position);
    }
    @NonNull
    @Override
    public FileViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_file, parent, false);
        return new FileViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull FileViewHolder holder, int position) {
        var fileInstance = fileList.get(position);
        fileInstance.setHolder(holder);
        holder.fileNameTextView.setText(fileInstance.getFileName());
        holder.removeButton.setOnClickListener(v -> {
            var adapterPosition = holder.getAdapterPosition();
            if (adapterPosition == RecyclerView.NO_POSITION) {
                return;
            }
            onRemove(adapterPosition);
        });
    }
    @Override
    public int getItemCount() {
        return fileList.size();
    }
    public static class FileViewHolder extends RecyclerView.ViewHolder {
        TextView fileNameTextView;
        ImageButton removeButton;
        ProgressBar progressBar;
        TextView textView;
        public FileViewHolder(@NonNull View itemView) {
            super(itemView);
            fileNameTextView = itemView.findViewById(R.id.fileNameTextView);
            removeButton = itemView.findViewById(R.id.removeButton);
            progressBar = itemView.findViewById(R.id.uploadProgressBar);
            textView = itemView.findViewById(R.id.uploadProgressTextView);
        }
    }
    public void onProgressChanged(Context context, FileInfo item, ProgressInfo progressInfo) {
        System.out.println("上传进度：" + progressInfo);
        // 在UI线程更新进度
        var progressPercentage = progressInfo.getProgressPercentage();
        ((AppCompatActivity) context).runOnUiThread(() -> {
            if (fileList.contains(item) && item.getHolder() != null) {//没被移除
                // 获取 ProgressBar
                // var view =  recyclerView.getLayoutManager().findViewByPosition(fileList.indexOf(item));
                var holder = item.getHolder();
                holder.textView.setText(progressPercentage + "%");
                // 设置 ProgressBar 进度
                holder.progressBar.setProgress(progressPercentage);
                if (progressPercentage >= 100) {
                    // 上传完成时隐藏 ProgressBar
                    holder.textView.setText("完成");
                    holder.progressBar.setVisibility(View.GONE);
                } else {
                    // 设置 ProgressBar 可见
                    holder.progressBar.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    public void addFile(Context context, Uri uri) {
        var item = new FileInfo(context, uri);
        fileList.add(item);
        notifyItemInserted(fileList.size() - 1);
        // 上传文件
        new Thread(() -> {//在新线程中上传文件，避免阻塞UI线程
            apiClient.addFile(item.getFileName(), item.getCreateInputStreamFunc(), progressInfo -> {
                onProgressChanged(context, item, progressInfo);
            });
        }).start();
    }
    private void onRemove(int position) {
        var item = fileList.get(position);
        fileList.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, fileList.size());
        onFileRemoveListener.onFileRemove(item);
    }
    public boolean isEmpty() {
        return fileList.isEmpty();
    }
}
